package filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import control.UserSession;

public class FBSFilter implements Filter {
    private FilterConfig filterConfig;
    private static final String FILTERED_REQUEST = "@@session_context_filtered_request";
    private static final String[] INHERENT_ESCAPE_URIS = { "/Authentication", "/Logout","/bootstrap" };

    public void doFilter(ServletRequest request, ServletResponse response,
                    FilterChain chain) throws IOException, ServletException {

            if (request != null && request.getAttribute(FILTERED_REQUEST) != null) {
                    chain.doFilter(request, response);
            } else {
                    request.setAttribute(FILTERED_REQUEST, Boolean.TRUE);
                    HttpServletRequest httpRequest = (HttpServletRequest) request;
                    UserSession userContext = (UserSession) httpRequest.getSession()
                                    .getAttribute("USERSESSION");

                    if (userContext == null && !isURILogin(httpRequest.getRequestURI(), httpRequest)) {
                            System.out.println(httpRequest.getRequestURI());
                            ((HttpServletResponse)response).sendRedirect(httpRequest.getContextPath());
                            return;
                    }else if(userContext!=null){
                    	//validate access rights.
                    	if((!userContext.isAdmin())&&httpRequest.getRequestURI().contains("Load")){
	                    	((HttpServletResponse)response).sendRedirect("noaccess.jsp");
	                    	return;
                    	}
                    }
                    
                    chain.doFilter(request, response);
            }
    }

    private boolean isURILogin(String requestURI, HttpServletRequest request) {
            if (request.getContextPath().equalsIgnoreCase(requestURI)
                            || (request.getContextPath() + "/")
                                            .equalsIgnoreCase(requestURI))
                    return true;
            for (String uri : INHERENT_ESCAPE_URIS) {
                    if (requestURI != null && requestURI.indexOf(uri) >= 0) {
                            return true;
                    }
            }
            return false;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
            this.filterConfig = filterConfig;
    }

    @Override
    public void destroy() {
            this.filterConfig = null;
    }
}